
<!DOCTYPE html>
<html lang="zh-Hans" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>React V16.3 即将更改的生命周期 - 默默默默燃</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="TriDiamond Obsidian,"> 
    <meta name="description" content="一枚前端搬砖队队员的记录册,即将更改的生命周期一年多来，React团队一直致力于实现异步渲染。上个月，他在JSConf冰岛的演讲中，丹揭示了一些令人兴奋的新的异步渲染可能性。现在，我们希望与您分享我们在学习这些功能时学到的一些,"> 
    <meta name="author" content="张白告丶"> 
    <link rel="alternative" href="atom.xml" title="默默默默燃" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    <link href="https://fonts.loli.net/css?family=Roboto+Mono|Rubik&display=swap" rel="stylesheet">
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1429596_nzgqgvnmkjb.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.7.2/animate.min.css">

    
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/codemirror.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/theme/dracula.css">

    
<link rel="stylesheet" href="/css/obsidian.css">

    
<link rel="stylesheet" href="/css/ball-atom.min.css">

<meta name="generator" content="Hexo 4.2.0"></head>


<body class="loading">
    <div class="loader">
        <div class="la-ball-atom la-2x">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <span id="config-title" style="display:none">默默默默燃</span>
    <div id="loader"></div>
    <div id="single">
    <div class="scrollbar gradient-bg-rev"></div>
<div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <div class="navigation animated fadeIn fast delay-1s">
        <img id="home-icon" class="icon-home" src="/img/favicon.png" alt="" data-url="https://zhanghao-web.github.io">
        <div id="play-icon" title="Play/Pause" class="iconfont icon-play"></div>
        <h3 class="subtitle">React V16.3 即将更改的生命周期</h3>
        <div class="social">
            <!--        <div class="like-icon">-->
            <!--            <a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
            <!--        </div>-->
            <div>
                <div class="share">
                    
                        <a href="javascript:;" class="iconfont icon-share1"></a>
                        <div class="share-component-cc" data-disabled="facebook,douban,linkedin,diandian,tencent,google"></div>
                    
                </div>
            </div>
        </div>
    </div>
</div>

    <div class="section">
        <div class=article-header-wrapper>
    <div class="article-header">
        <div class="article-cover animated fadeIn" style="
            animation-delay: 600ms;
            animation-duration: 1.2s;
            background-image: 
                radial-gradient(ellipse closest-side, rgba(0, 0, 0, 0.65), #100e17),
                url(/img/cover.jpg) ">
        </div>
        <div class="else">
            <p class="animated fadeInDown">
                
                <a href="/categories/React"><b>「
                    </b>REACT<b> 」</b></a>
                
                April 30, 2018
            </p>
            <h3 class="post-title animated fadeInDown"><a href="/2018/04/30/React/React-V16-3-%E5%8D%B3%E5%B0%86%E6%9B%B4%E6%94%B9%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/" title="React V16.3 即将更改的生命周期" class="">React V16.3 即将更改的生命周期</a>
            </h3>
            
            <p class="post-count animated fadeInDown">
                
                <span>
                    <b class="iconfont icon-text2"></b> <i>Words count</i>
                    83k
                </span>
                
                
                <span>
                    <b class="iconfont icon-timer__s"></b> <i>Reading time</i>
                    1:15
                </span>
                
                
                
                <span id="busuanzi_container_page_pv">
                    <b class="iconfont icon-read"></b> <i>Read count</i>
                    <span id="busuanzi_value_page_pv">0</span>
                </span>
                
            </p>
            
            
            <ul class="animated fadeInDown post-tags-list" itemprop="keywords"><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/React/" rel="tag">React</a></li></ul>
            
        </div>
    </div>
</div>

<div class="screen-gradient-after">
    <div class="screen-gradient-content">
        <div class="screen-gradient-content-inside">
            <div class="bold-underline-links screen-gradient-sponsor">
                <p>
                    <span class="animated fadeIn delay-1s"></span>
                </p>
            </div>
        </div>
    </div>
</div>

<div class="article">
    <div class='main'>
        <div class="content markdown animated fadeIn">
            <h1 id="即将更改的生命周期"><a href="#即将更改的生命周期" class="headerlink" title="即将更改的生命周期"></a>即将更改的生命周期</h1><p>一年多来，React团队一直致力于实现异步渲染。上个月，他在JSConf冰岛的演讲中，丹揭示了一些令人兴奋的新的异步渲染可能性。现在，我们希望与您分享我们在学习这些功能时学到的一些经验教训，以及一些帮助您准备组件以在启动时进行异步渲染的方法。</p>
<p>我们了解到的最大问题之一是，我们的一些传统组件生命周期会导致一些不安全的编码实践。他们是：</p>
<ul>
<li>componentWillMount</li>
<li>componentWillReceiveProps</li>
<li>componentWillUpdate</li>
</ul>
<p>这些生命周期方法经常被误解和滥用;此外，我们预计他们的潜在滥用可能在异步渲染方面有更大的问题。因此，我们将在即将发布的版本中为这些生命周期添加一个“<code>UNSAFE_</code>”前缀。 （这里，“不安全”不是指安全性，而是表示使用这些生命周期的代码将更有可能在未来的React版本中存在缺陷，特别是一旦启用了异步渲染）。</p>
<h2 id="逐步迁移路径"><a href="#逐步迁移路径" class="headerlink" title="逐步迁移路径"></a>逐步迁移路径</h2><p>React遵循语义版本控制, 所以这种改变将是渐进的。我们目前的计划是：</p>
<ul>
<li><p><strong>16.3</strong>：为不安全生命周期引入别名UNSAFE_componentWillMount，UNSAFE_componentWillReceiveProps和UNSAFE_componentWillUpdate。 （旧的生命周期名称和新的别名都可以在此版本中使用。）</p>
</li>
<li><p><strong>未来的16.x版本</strong>：为componentWillMount，componentWillReceiveProps和componentWillUpdate启用弃用警告。 （旧的生命周期名称和新的别名都可以在此版本中使用，但旧名称会记录DEV模式警告。）</p>
</li>
<li><p><strong>17.0</strong>：删除componentWillMount，componentWillReceiveProps和componentWillUpdate。 （从现在开始，只有新的“UNSAFE_”生命周期名称将起作用。）</p>
</li>
</ul>
<p><strong>请注意，如果您是React应用程序开发人员，那么您不必对遗留方法进行任何操作。即将发布的16.3版本的主要目的是让开源项目维护人员在任何弃用警告之前更新其库。这些警告将在未来的16.x版本发布之前不会启用</strong>。</p>
<h2 id="从传统生命周期迁移"><a href="#从传统生命周期迁移" class="headerlink" title="从传统生命周期迁移"></a>从传统生命周期迁移</h2><p>如果您想开始使用React 16.3中引入的新组件API（或者如果您是维护人员提前更新库），以下是一些示例，我们希望这些示例可以帮助您开始考虑组件的变化。随着时间的推移，我们计划在文档中添加额外的“配方”，以展示如何以避免有问题的生命周期的方式执行常见任务。</p>
<p>在开始之前，我们将简要概述为16.3版计划的生命周期更改：</p>
<ul>
<li>我们正在添加以下生命周期别名：</li>
</ul>
<p>(1) UNSAFE_componentWillMount，</p>
<p>(2) UNSAFE_componentWillReceiveProps</p>
<p>(3) UNSAFE_componentWillUpdate。 （旧的生命周期名称和新的别名都将受支持。）</p>
<ul>
<li>我们介绍了两个新的生命周期，分别是getDerivedStateFromProps和getSnapshotBeforeUpdate。</li>
</ul>
<h3 id="新的生命周期-getDerivedStateFromProps"><a href="#新的生命周期-getDerivedStateFromProps" class="headerlink" title="新的生命周期: getDerivedStateFromProps"></a>新的生命周期: getDerivedStateFromProps</h3><a id="more"></a>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Example</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">static</span> getDerivedStateFromProps(nextProps, prevState) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>新的静态<code>getDerivedStateFromProps</code>生命周期在组件实例化以及接收新<code>props</code>后调用。它可以返回一个对象来更新<code>state</code>，或者返回null来表示新的<code>props</code>不需要任何<code>state</code>更新。</p>
<p>与<code>componentDidUpdate</code>一起，这个新的生命周期应该覆盖传统<code>componentWillReceiveProps</code>的所有用例。</p>
<h3 id="新的生命周期-getSnapshotBeforeUpdate"><a href="#新的生命周期-getSnapshotBeforeUpdate" class="headerlink" title="新的生命周期: getSnapshotBeforeUpdate"></a>新的生命周期: getSnapshotBeforeUpdate</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Example</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  getSnapshotBeforeUpdate(prevProps, prevState) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>新的<code>getSnapshotBeforeUpdate</code>生命周期在更新之前被调用（例如，在DOM被更新之前）。此生命周期的返回值将作为第三个参数传递给<code>componentDidUpdate</code>。 （这个生命周期不是经常需要的，但可以用于在恢复期间手动保存滚动位置的情况。）</p>
<p>You can find their type signatures in this gist.</p>
<p>我们看看如何在使用这两种生命周期的，例子如下:</p>
<h4 id="例如"><a href="#例如" class="headerlink" title="例如"></a>例如</h4><ul>
<li><p>Initializing state（初始化状态）Ini</p>
</li>
<li><p>Fetching external data（获取外部数据）</p>
</li>
<li><p>Adding event listeners（添加事件监听）</p>
</li>
<li><p>Updating state based on props（基于props更新state）</p>
</li>
<li><p>Invoking external callbacks(调用外部的callbacks)</p>
</li>
<li><p>Side effects on props change</p>
</li>
<li><p>Fetching external data when props change（props改变时获取外部数据）</p>
</li>
<li><p>Reading DOM properties before an update(在更新之前读取DOM属性)</p>
</li>
</ul>
<blockquote>
<p>注意<br>为简洁起见，下面的示例是使用实验类属性转换编写的，但如果没有它，则应用相同的迁移策略。</p>
</blockquote>
<h3 id="初始化状态："><a href="#初始化状态：" class="headerlink" title="初始化状态："></a>初始化状态：</h3><p>这个例子展示了一个调用<code>componentWillMount</code>中带有<code>setState</code>的组件：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Before</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  state = &#123;&#125;;</span><br><span class="line"></span><br><span class="line">  componentWillMount() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.setState(&#123;</span><br><span class="line"></span><br><span class="line">      currentColor: <span class="keyword">this</span>.props.defaultColor,</span><br><span class="line"></span><br><span class="line">      palette: <span class="string">'rgb'</span>,</span><br><span class="line"></span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这种类型的组件最简单的重构是将状态初始化移动到构造函数或属性初始值设定项，如下所示：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// After</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  state = &#123;</span><br><span class="line"></span><br><span class="line">    currentColor: <span class="keyword">this</span>.props.defaultColor,</span><br><span class="line"></span><br><span class="line">    palette: <span class="string">'rgb'</span>,</span><br><span class="line"></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="获取外部数据"><a href="#获取外部数据" class="headerlink" title="获取外部数据"></a>获取外部数据</h3><p>以下是使用componentWillMount获取外部数据的组件示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Before</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  state = &#123;</span><br><span class="line"></span><br><span class="line">    externalData: <span class="literal">null</span>,</span><br><span class="line"></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  componentWillMount() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>._asyncRequest = asyncLoadData().then(</span><br><span class="line"></span><br><span class="line">      externalData =&gt; &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>._asyncRequest = <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.setState(&#123;externalData&#125;);</span><br><span class="line"></span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  componentWillUnmount() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>._asyncRequest) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>._asyncRequest.cancel();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  render() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.state.externalData === <span class="literal">null</span>) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Render loading state ...</span></span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Render real UI ...</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>对于大多数用例，建议的升级路径是将数据提取移入<code>componentDidMount</code>：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// After</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  state = &#123;</span><br><span class="line"></span><br><span class="line">    externalData: <span class="literal">null</span>,</span><br><span class="line"></span><br><span class="line">  &#125;;</span><br><span class="line">  componentDidMount() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>._asyncRequest = asyncLoadData().then(</span><br><span class="line"></span><br><span class="line">      externalData =&gt; &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>._asyncRequest = <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.setState(&#123;externalData&#125;);</span><br><span class="line"></span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  componentWillUnmount() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>._asyncRequest) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>._asyncRequest.cancel();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  render() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.state.externalData === <span class="literal">null</span>) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Render loading state ...</span></span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Render real UI ...</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>有一个常见的错误观念认为，在<code>componentWillMount</code>中提取可以避免第一个空的渲染。在实践中，这从来都不是真的，因为React总是在<code>componentWillMount</code>之后立即执行渲染。如果数据在<code>componentWillMount</code>触发的时间内不可用，则无论你在哪里提取数据，第一个渲染仍将显示加载状态。这就是为什么在绝大多数情况下将提取移到<code>componentDidMount</code>没有明显效果。</p>
<blockquote>
<p>注意：<br>一些高级用例（例如，像Relay这样的库）可能想要尝试使用热切的预取异步数据。在这里可以找到一个这样做的例子。</p>
</blockquote>
<p>当支持服务器渲染时，目前需要同步提供数据 - <code>componentWillMount</code>通常用于此目的，但构造函数可以用作替换。即将到来的悬念API将使得异步数据在客户端和服务器呈现中都可以清晰地获取。</p>
<h3 id="添加时间监听"><a href="#添加时间监听" class="headerlink" title="添加时间监听"></a>添加时间监听</h3><p>下面是一个在安装时监听外部事件调度程序的组件示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Before</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  componentWillMount() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.setState(&#123;</span><br><span class="line"></span><br><span class="line">      subscribedValue: <span class="keyword">this</span>.props.dataSource.value,</span><br><span class="line"></span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">// This is not safe; it can leak!</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.props.dataSource.subscribe(</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.handleSubscriptionChange</span><br><span class="line"></span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  componentWillUnmount() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.props.dataSource.unsubscribe(</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.handleSubscriptionChange</span><br><span class="line"></span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  handleSubscriptionChange = <span class="function"><span class="params">dataSource</span> =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.setState(&#123;</span><br><span class="line"></span><br><span class="line">      subscribedValue: dataSource.value,</span><br><span class="line"></span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>不幸的是，这会导致服务器渲染（<code>componentWillUnmount</code>永远不会被调用）和异步渲染（在渲染完成之前渲染可能被中断，导致<code>componentWillUnmount</code>不被调用）的内存泄漏。</p>
<p>人们经常认为<code>componentWillMount</code>和<code>componentWillUnmount</code>总是配对，但这并不能保证。只有调用<code>componentDidMount</code>后，React才能保证稍后调用<code>componentWillUnmount</code>进行清理。</p>
<p>出于这个原因，添加事件监听的推荐方式是使用<code>componentDidMount</code>生命周期：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// After</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  state = &#123;</span><br><span class="line"></span><br><span class="line">    subscribedValue: <span class="keyword">this</span>.props.dataSource.value,</span><br><span class="line"></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  componentDidMount() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Event listeners are only safe to add after mount,</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// So they won't leak if mount is interrupted or errors.</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.props.dataSource.subscribe(</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.handleSubscriptionChange</span><br><span class="line"></span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">// External values could change between render and mount,</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// In some cases it may be important to handle this case.</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.state.subscribedValue !==</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.props.dataSource.value</span><br><span class="line"></span><br><span class="line">    ) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.setState(&#123;</span><br><span class="line"></span><br><span class="line">        subscribedValue: <span class="keyword">this</span>.props.dataSource.value,</span><br><span class="line"></span><br><span class="line">      &#125;);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  componentWillUnmount() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.props.dataSource.unsubscribe(</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.handleSubscriptionChange</span><br><span class="line"></span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  handleSubscriptionChange = <span class="function"><span class="params">dataSource</span> =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.setState(&#123;</span><br><span class="line"></span><br><span class="line">      subscribedValue: dataSource.value,</span><br><span class="line"></span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>有时候更新监听以响应属性变化很重要。如果您使用的是像Redux或MobX这样的库，库的容器组件会为您处理。对于应用程序作者，我们创建了一个小型库<code>create-subscription</code>来帮助解决这个问题。我们会将它与React 16.3一起发布。</p>
<p>我们可以使用<code>create-subscription</code>来传递监听的值，而不是像上例那样传递监听 的<code>dataSource prop</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;createSubscription&#125; <span class="keyword">from</span> <span class="string">'create-subscription'</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> Subscription = createSubscription(&#123;</span><br><span class="line"></span><br><span class="line">  getCurrentValue(sourceProp) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Return the current value of the subscription (sourceProp).</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> sourceProp.value;</span><br><span class="line"></span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  subscribe(sourceProp, callback) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">handleSubscriptionChange</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">      callback(sourceProp.value);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Subscribe (e.g. add an event listener) to the subscription (sourceProp).</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Call callback(newValue) whenever a subscription changes.</span></span><br><span class="line"></span><br><span class="line">    sourceProp.subscribe(handleSubscriptionChange);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Return an unsubscribe method.</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">unsubscribe</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">      sourceProp.unsubscribe(handleSubscriptionChange);</span><br><span class="line"></span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// Rather than passing the subscribable source to our ExampleComponent,</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// We could just pass the subscribed value directly:</span></span><br><span class="line"></span><br><span class="line"><span class="string">`&lt;Subscription source=&#123;dataSource&#125;&gt;`</span></span><br><span class="line"></span><br><span class="line">  &#123;value =&gt; <span class="string">`&lt;ExampleComponent subscribedValue=&#123;value&#125; /&gt;`</span>&#125;</span><br><span class="line"></span><br><span class="line"><span class="string">`&lt;/Subscription&gt;`</span>;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意<br>像Relay / Apollo这样的库应该使用与创建订阅相同的技术手动管理订阅（如此处所引用的），并采用最适合其库使用的优化方式。</p>
</blockquote>
<h3 id="基于props更新state"><a href="#基于props更新state" class="headerlink" title="基于props更新state"></a>基于props更新state</h3><p>以下是使用旧版<code>componentWillReceiveProps</code>生命周期基于新的道具值更新状态的组件示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Before</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  state = &#123;</span><br><span class="line"></span><br><span class="line">    isScrollingDown: <span class="literal">false</span>,</span><br><span class="line"></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  componentWillReceiveProps(nextProps) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.props.currentRow !== nextProps.currentRow) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.setState(&#123;</span><br><span class="line"></span><br><span class="line">        isScrollingDown:</span><br><span class="line"></span><br><span class="line">          nextProps.currentRow &gt; <span class="keyword">this</span>.props.currentRow,</span><br><span class="line"></span><br><span class="line">      &#125;);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>尽管上面的代码本身并没有问题，但<code>componentWillReceiveProps</code>生命周期通常会被错误地用于解决问题。因此，该方法将被弃用。</p>
<p>从版本16.3开始，<code>更新state以响应props</code>更改的推荐方法是使用新的静态<code>getDerivedStateFromProps</code>生命周期。 （生命周期在组件创建时以及每次收到新道具时调用）：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// After</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// Initialize state in constructor,</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// Or with a property initializer.</span></span><br><span class="line"></span><br><span class="line">  state = &#123;</span><br><span class="line"></span><br><span class="line">    isScrollingDown: <span class="literal">false</span>,</span><br><span class="line"></span><br><span class="line">    lastRow: <span class="literal">null</span>,</span><br><span class="line"></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="keyword">static</span> getDerivedStateFromProps(nextProps, prevState) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (nextProps.currentRow !== prevState.lastRow) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> &#123;</span><br><span class="line"></span><br><span class="line">        isScrollingDown:</span><br><span class="line"></span><br><span class="line">          nextProps.currentRow &gt; prevState.lastRow,</span><br><span class="line"></span><br><span class="line">        lastRow: nextProps.currentRow,</span><br><span class="line"></span><br><span class="line">      &#125;;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Return null to indicate no change to state.</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>你可能会注意到在上面的例子中，<code>props.currentRow</code>是一个镜像状态（如state.lastRow）。这使得<code>getDerivedStateFromProps</code>可以像在<code>componentWillReceiveProps</code>中一样访问以前的props值。</p>
<p>您可能想知道为什么我们不只是将先前的<code>props</code>作为参数传递给<code>getDerivedStateFromProps</code>。我们在设计API时考虑了这个选项，但最终决定反对它，原因有两个</p>
<ul>
<li><p>在第一次调用getDerivedStateFromProps（实例化后）时，prevProps参数将为null，需要在访问prevProps时添加if-not-null检查。</p>
</li>
<li><p>没有将以前的props传递给这个函数，在未来版本的React中释放内存的一个步骤。 （如果React不需要将先前的道具传递给生命周期，那么它不需要将先前的道具对象保留在内存中。）</p>
</li>
</ul>
<blockquote>
<p>Note<br>如果您正在编写共享组件，那么react-lifecycles-compat polyfill可以使新的getDerivedStateFromProps生命周期与旧版本的React一起使用。详细了解如何在下面使用它。</p>
</blockquote>
<h3 id="调用外部回调函数"><a href="#调用外部回调函数" class="headerlink" title="调用外部回调函数"></a>调用外部回调函数</h3><p>下面是一个在内部状态发生变化时调用外部函数的组件示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Before</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  componentWillUpdate(nextProps, nextState) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.state.someStatefulValue !==</span><br><span class="line"></span><br><span class="line">      nextState.someStatefulValue</span><br><span class="line"></span><br><span class="line">    ) &#123;</span><br><span class="line"></span><br><span class="line">      nextProps.onChange(nextState.someStatefulValue);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在异步模式下使用<code>componentWillUpdate</code>都是不安全的，因为外部回调可能会多次调用只更新一次。相反，应该使用<code>componentDidUpdate</code>生命周期，因为它保证每次更新只调用一次：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// After</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  componentDidUpdate(prevProps, prevState) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.state.someStatefulValue !==</span><br><span class="line"></span><br><span class="line">      prevState.someStatefulValue</span><br><span class="line"></span><br><span class="line">    ) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.props.onChange(<span class="keyword">this</span>.state.someStatefulValue);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="props改变的副作用"><a href="#props改变的副作用" class="headerlink" title="props改变的副作用"></a>props改变的副作用</h3><p>与上述 事例类似，有时组件在道具更改时会产生副作用。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Before</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  componentWillReceiveProps(nextProps) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.props.isVisible !== nextProps.isVisible) &#123;</span><br><span class="line"></span><br><span class="line">      logVisibleChange(nextProps.isVisible);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>与<code>componentWillUpdate</code>一样，<code>componentWillReceiveProps</code>可能会多次调用但是只更新一次。出于这个原因，避免在此方法中导致的副作用非常重要。相反，应该使用<code>componentDidUpdate</code>，因为它保证每次更新只调用一次：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// After</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  componentDidUpdate(prevProps, prevState) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.props.isVisible !== prevProps.isVisible) &#123;</span><br><span class="line"></span><br><span class="line">      logVisibleChange(<span class="keyword">this</span>.props.isVisible);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="props改变时获取外部数据"><a href="#props改变时获取外部数据" class="headerlink" title="props改变时获取外部数据"></a>props改变时获取外部数据</h3><p>以下是根据<code>propsvalues</code>提取外部数据的组件示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Before</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  state = &#123;</span><br><span class="line"></span><br><span class="line">    externalData: <span class="literal">null</span>,</span><br><span class="line"></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  componentDidMount() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>._loadAsyncData(<span class="keyword">this</span>.props.id);</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  componentWillReceiveProps(nextProps) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (nextProps.id !== <span class="keyword">this</span>.props.id) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.setState(&#123;<span class="attr">externalData</span>: <span class="literal">null</span>&#125;);</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>._loadAsyncData(nextProps.id);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  componentWillUnmount() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>._asyncRequest) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>._asyncRequest.cancel();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  render() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.state.externalData === <span class="literal">null</span>) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Render loading state ...</span></span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Render real UI ...</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  _loadAsyncData(id) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>._asyncRequest = asyncLoadData(id).then(</span><br><span class="line"></span><br><span class="line">      externalData =&gt; &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>._asyncRequest = <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.setState(&#123;externalData&#125;);</span><br><span class="line"></span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此组件的推荐升级路径是将数据更新移动到<code>componentDidUpdate</code>中。在渲染新道具之前，您还可以使用新的<code>getDerivedStateFromProps</code>生命周期清除陈旧的数据：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// After</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  state = &#123;</span><br><span class="line"></span><br><span class="line">    externalData: <span class="literal">null</span>,</span><br><span class="line"></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="keyword">static</span> getDerivedStateFromProps(nextProps, prevState) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Store prevId in state so we can compare when props change.</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Clear out previously-loaded data (so we don't render stale stuff).</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (nextProps.id !== prevState.prevId) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> &#123;</span><br><span class="line"></span><br><span class="line">        externalData: <span class="literal">null</span>,</span><br><span class="line"></span><br><span class="line">        prevId: nextProps.id,</span><br><span class="line"></span><br><span class="line">      &#125;;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">// No state update necessary</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  componentDidMount() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>._loadAsyncData(<span class="keyword">this</span>.props.id);</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  componentDidUpdate(prevProps, prevState) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.state.externalData === <span class="literal">null</span>) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>._loadAsyncData(<span class="keyword">this</span>.props.id);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  componentWillUnmount() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>._asyncRequest) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>._asyncRequest.cancel();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  render() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.state.externalData === <span class="literal">null</span>) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Render loading state ...</span></span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Render real UI ...</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  _loadAsyncData(id) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>._asyncRequest = asyncLoadData(id).then(</span><br><span class="line"></span><br><span class="line">      externalData =&gt; &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>._asyncRequest = <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.setState(&#123;externalData&#125;);</span><br><span class="line"></span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意<br>如果您使用支持取消的HTTP库（如axios），那么卸载时取消正在进行的请求很简单。对于原生Promise，您可以使用如下所示的方法。</p>
</blockquote>
<h3 id="在更新之前读取DOM属性"><a href="#在更新之前读取DOM属性" class="headerlink" title="在更新之前读取DOM属性"></a>在更新之前读取DOM属性</h3><p>下面是一个组件的例子，它在更新之前从DOM中读取属性，以便在列表中保持滚动位置：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line">componentWillUpdate(nextProps, nextState) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Are we adding new items to the list?</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Capture the scroll position so we can adjust scroll later.</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.props.list.length &lt; nextProps.list.length) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.previousScrollOffset =</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.listRef.scrollHeight - <span class="keyword">this</span>.listRef.scrollTop;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  componentDidUpdate(prevProps, prevState) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// If previousScrollOffset is set, we've just added new items.</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Adjust scroll so these new items don't push the old ones out of view.</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.previousScrollOffset !== <span class="literal">null</span>) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.listRef.scrollTop =</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.listRef.scrollHeight -</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.previousScrollOffset;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.previousScrollOffset = <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  render() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line"></span><br><span class="line">      <span class="string">`&lt;div&gt;`</span></span><br><span class="line"></span><br><span class="line">        &#123;<span class="comment">/* ...contents... */</span>&#125;</span><br><span class="line"></span><br><span class="line">      <span class="string">`&lt;/div&gt;`</span></span><br><span class="line"></span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  setListRef = <span class="function"><span class="params">ref</span> =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.listRef = ref;</span><br><span class="line"></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在上面的例子中，<code>componentWillUpdate</code>被用来读取DOM属性。但是，对于异步渲染，“render”阶段生命周期（如c<code>omponentWillUpdate</code>和<code>render</code>）与“commit”阶段生命周期（如<code>componentDidUpdate</code>）之间可能存在延迟。如果用户在这段时间内做了类似调整窗口大小的操作，则从<code>componentWillUpdate</code>中读取的<code>scrollHeight</code>值将失效。</p>
<p>解决此问题的方法是使用新的“commit”阶段生命周期<code>getSnapshotBeforeUpdate</code>。在数据发生变化之前立即调用该方法（例如，在更新DOM之前）。它可以将React的值作为参数传递给<code>componentDidUpdate</code>，在数据发生变化后立即调用它。</p>
<p>这两个生命周期可以像这样一起使用：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ScrollingList</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  listRef = <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  getSnapshotBeforeUpdate(prevProps, prevState) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Are we adding new items to the list?</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Capture the scroll position so we can adjust scroll later.</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (prevProps.list.length &lt; <span class="keyword">this</span>.props.list.length) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> (</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.listRef.scrollHeight - <span class="keyword">this</span>.listRef.scrollTop</span><br><span class="line"></span><br><span class="line">      );</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  componentDidUpdate(prevProps, prevState, snapshot) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// If we have a snapshot value, we've just added new items.</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Adjust scroll so these new items don't push the old ones out of view.</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// (snapshot here is the value returned from getSnapshotBeforeUpdate)</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (snapshot !== <span class="literal">null</span>) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.listRef.scrollTop =</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.listRef.scrollHeight - snapshot;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  render() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line"></span><br><span class="line">      <span class="string">`&lt;div&gt;`</span></span><br><span class="line"></span><br><span class="line">        &#123;<span class="comment">/* ...contents... */</span>&#125;</span><br><span class="line"></span><br><span class="line">      <span class="string">`&lt;/div&gt;`</span></span><br><span class="line"></span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  setListRef = <span class="function"><span class="params">ref</span> =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.listRef = ref;</span><br><span class="line"></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意<br>如果您正在编写共享组件，那么<code>react-lifecycles-compat polyfill</code>可以使新的<code>getSnapshotBeforeUpdate</code>生命周期与旧版本的React一起使用。详细了解如何使用它。</p>
</blockquote>
<h2 id="其它情况"><a href="#其它情况" class="headerlink" title="其它情况"></a>其它情况</h2><p>除了以上的一些常见的例子，还可能会有别的情况本篇文章没有涵盖到，如果您以本博文未涉及的方式使用除了以上 <code>componentWillMount</code>，<code>componentWillUpdate</code>或<code>componentWillReceiveProps</code>，并且不确定如何迁移这些传统生命周期，你可以提供您的代码示例和我们的文档，并且一起提交一个新问题。我们将在更新这份文件时提供新的替代模式。</p>
<p>当React 16.3发布时，我们还将发布一个新的npm包， react-lifecycles-compat。该npm包会填充组件，以便新的getDerivedStateFromProps和getSnapshotBeforeUpdate生命周期也可以与旧版本的React（0.14.9+）一起使用。</p>
<p>要使用这个polyfill，首先将它作为依赖项添加到您的库中：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"># Yarn</span><br><span class="line"></span><br><span class="line">yarn add react-lifecycles-compat</span><br><span class="line"></span><br><span class="line"># NPM</span><br><span class="line"></span><br><span class="line">npm install react-lifecycles-compat --save</span><br></pre></td></tr></table></figure>
<p>接下来，更新您的组件以使用新的生命周期（如上所述）。</p>
<p>最后，使用polyfill将组件向后兼容旧版本的React：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> &#123;polyfill&#125; <span class="keyword">from</span> <span class="string">'react-lifecycles-compat'</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">static</span> getDerivedStateFromProps(nextProps, prevState) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Your state update logic here ...</span></span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Polyfill your component to work with older versions of React:</span></span><br><span class="line"></span><br><span class="line">polyfill(ExampleComponent);</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> ExampleComponent;</span><br></pre></td></tr></table></figure>
<p><a href="https://mp.weixin.qq.com/s/dYVdOGtcka3_ODfap1pvJQ" target="_blank" rel="noopener">原文地址</a></p>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls"
                data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
            <ul id="audio-list" style="display:none">
                
                
                <li title='0' data-url='/statics/chengdu.mp3'></li>
                
                    
            </ul>
            
            
            
    <div id='gitalk-container' class="comment link"
        data-ae='true'
        data-ci='ec894e2b66f752e8b7fb'
        data-cs='3ccc2e92bb350688fe2c2dc2930189b62622bfb1'
        data-r='blog-comments'
        data-o='TriDiamond'
        data-a='TriDiamond'
        data-d='undefined'
    >Comments</div>


            
            
        </div>
        <div class="sidebar">
            <div class="box animated fadeInRight">
                <div class="subbox">
                    <img src="https://res.cloudinary.com/tridiamond/image/upload/v1573019751/TriDiamond_logo_ui_xeublz.jpg" height=300 width=300></img>
                    <p>张白告丶</p>
                    <span>Think like an artist, develop like an artisan</span>
                    <dl>
                        <dd><a href="https://github.com/zhanghao-web" target="_blank"><span
                                    class=" iconfont icon-github"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-twitter"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-stack-overflow"></span></a></dd>
                    </dl>
                </div>
                <ul>
                    <li><a href="/">149 <p>Articles</p></a></li>
                    <li><a href="/categories">23 <p>Categories</p></a></li>
                    <li><a href="/tags">47 <p>Tags</p></a></li>
                </ul>
            </div>
            
            
            
            <div class="box sticky animated fadeInRight faster">
                <div id="toc" class="subbox">
                    <h4>Contents</h4>
                    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#即将更改的生命周期"><span class="toc-number">1.</span> <span class="toc-text">即将更改的生命周期</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#逐步迁移路径"><span class="toc-number">1.1.</span> <span class="toc-text">逐步迁移路径</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#从传统生命周期迁移"><span class="toc-number">1.2.</span> <span class="toc-text">从传统生命周期迁移</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#新的生命周期-getDerivedStateFromProps"><span class="toc-number">1.2.1.</span> <span class="toc-text">新的生命周期: getDerivedStateFromProps</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#新的生命周期-getSnapshotBeforeUpdate"><span class="toc-number">1.2.2.</span> <span class="toc-text">新的生命周期: getSnapshotBeforeUpdate</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#初始化状态："><span class="toc-number">1.2.3.</span> <span class="toc-text">初始化状态：</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#获取外部数据"><span class="toc-number">1.2.4.</span> <span class="toc-text">获取外部数据</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#添加时间监听"><span class="toc-number">1.2.5.</span> <span class="toc-text">添加时间监听</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#基于props更新state"><span class="toc-number">1.2.6.</span> <span class="toc-text">基于props更新state</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#调用外部回调函数"><span class="toc-number">1.2.7.</span> <span class="toc-text">调用外部回调函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#props改变的副作用"><span class="toc-number">1.2.8.</span> <span class="toc-text">props改变的副作用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#props改变时获取外部数据"><span class="toc-number">1.2.9.</span> <span class="toc-text">props改变时获取外部数据</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#在更新之前读取DOM属性"><span class="toc-number">1.2.10.</span> <span class="toc-text">在更新之前读取DOM属性</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#其它情况"><span class="toc-number">1.3.</span> <span class="toc-text">其它情况</span></a></li></ol></li></ol>
                </div>
            </div>
            
            
        </div>
    </div>
</div>

    </div>
</div>
    <div id="back-to-top" class="animated fadeIn faster">
        <div class="flow"></div>
        <span class="percentage animated fadeIn faster">0%</span>
        <span class="iconfont icon-top02 animated fadeIn faster"></span>
    </div>
</body>
<footer>
    <p class="copyright" id="copyright">
        &copy; 2020
        <span class="gradient-text">
            张白告丶
        </span>.
        Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
        Theme
        <span class="gradient-text">
            <a href="https://github.com/TriDiamond/hexo-theme-obsidian" title="Obsidian" target="_blank" rel="noopener">Obsidian</a>
        </span>
        <small><a href="https://github.com/TriDiamond/hexo-theme-obsidian/blob/master/CHANGELOG.md" title="v1.4.3" target="_blank" rel="noopener">v1.4.3</a></small>
    </p>
</footer>

<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.6/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["STIX", "TeX"],
      linebreaks: {
        automatic: true
      },
      EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
      inlineMath: [
        ["$", "$"],
        ["\\(", "\\)"]
      ],
      processEscapes: true,
      ignoreClass: "tex2jax_ignore|dno",
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      noUndefined: {
        attributes: {
          mathcolor: "red",
          mathbackground: "#FFEEEE",
          mathsize: "90%"
        }
      },
      Macros: {
        href: "{}"
      }
    },
    messageStyle: "none"
  });
</script>
<script>
  function initialMathJax() {
    MathJax.Hub.Queue(function () {
      var all = MathJax.Hub.getAllJax(),
        i;
      // console.log(all);
      for (i = 0; i < all.length; i += 1) {
        console.log(all[i].SourceElement().parentNode)
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  }

  function reprocessMathJax() {
    if (typeof MathJax !== 'undefined') {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
  }
</script>



    
<link rel="stylesheet" href="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.css">

    
<script src="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.js"></script>



<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/obsidian.js"></script>
<script src="/js/jquery.truncate.js"></script>
<script src="/js/search.js"></script>


<script src="//cdn.bootcss.com/typed.js/2.0.10/typed.min.js"></script>


<script src="//cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>


<script src="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>


<script src="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.min.js"></script>

    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/css/css.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/xml/xml.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/htmlmixed/htmlmixed.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/clike/clike.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/php/php.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/shell/shell.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/python/python.min.js"></script>




    
<script src="/js/busuanzi.min.js"></script>

    <script>
        $(document).ready(function () {
            if ($('span[id^="busuanzi_"]').length) {
                initialBusuanzi();
            }
        });
    </script>



<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/default-skin/default-skin.min.css">


<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="//www.googletagmanager.com/gtag/js?id=UA-149874671-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-149874671-1');
    </script>





<script>
    function initialTyped () {
        var typedTextEl = $('.typed-text');
        if (typedTextEl && typedTextEl.length > 0) {
            var typed = new Typed('.typed-text', {
                strings: ["Think like an artist, develop like an artisan", "艺术家思维去思考问题，工匠创造精神去开发"],
                typeSpeed: 90,
                loop: true,
                loopCount: Infinity,
                backSpeed: 20,
            });
        }
    }

    if ($('.article-header') && $('.article-header').length) {
        $(document).ready(function () {
            initialTyped();
        });
    }
</script>




</html>
